package com.xiangban.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiangban.dao.*;
import com.xiangban.exception.BizException;
import com.xiangban.model.*;
import com.xiangban.model.dto.*;
import com.xiangban.model.res.ApiResultCode;
import com.xiangban.model.vo.PersonalCenterVo;
import com.xiangban.service.AccompanyService;
import com.xiangban.util.CommonUtil;
import com.xiangban.util.PageUtils;
import com.xiangban.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.xiangban.util.CommonUtil.BizEmpty;

/**
 * @Author ly
 * @date 2021/12/8 10:55
 */
@Service
@Slf4j
public class AccompanyServiceImpl implements AccompanyService {
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private AccompanyMapper accompanyMapper;
    @Autowired
    private AccompanyReceiveOrderMapper accompanyReceiveOrderMapper;
    @Autowired
    private AccompanyWalletMapper accompanyWalletMapper;
    @Autowired
    private AccompanyReceiveStatusMapper accompanyReceiveStatusMapper;
    @Autowired
    private AccompanyInviteMapper accompanyInviteMapper;
    private static Integer money = 5;
    @Autowired
    private PageUtils pageUtils;
    @Autowired
    private TUserMappers tUserMappers;
    @Autowired
    private  OrderMapper orderMapper;
    @Autowired
    private CommonUtils commonUtils;


    /**
     * 陪诊人员认证
     */

    @Override
    @Transactional
    public Object accompanyAttestation(AccompanyDto accompanyDto) throws Exception {
        //需要的参数 身份证号 姓名 性别 手机  身份证正反面 健康证 工作照片 地址

            boolean OkOrNo = notNull(accompanyDto);//非空判断
            if (!OkOrNo) {
                throw new BizException(ApiResultCode.COMMON_PARAM_NULL);
            }
        Boolean aBoolean = commonUtil.checkIdCard(accompanyDto.getIdCard(), accompanyDto.getName());
            if (!aBoolean){
                throw  new BizException(ApiResultCode.ID_CARD_AND_NAME_INCONSISTENT);
            }
        //查询有没有相同姓名 或者 身份证号 或者手机号相同的
            String userId = commonUtil.getUserId(request);
            UserAccompany userAccompany = new UserAccompany();
            userAccompany.setUid(Integer.parseInt(userId));
          UserAccompany userAccompany1=  accompanyMapper.getAccompanyByUidandeStatus(userAccompany);//根据uid 查询有没有 认证陪诊 除了审核失败的
         if(!BizEmpty(userAccompany1)&&(userAccompany1.getStatus()==0||userAccompany1.getStatus()==1)){
            throw  new BizException(ApiResultCode.DUPLICATECLAIM);
          }
         if (!BizEmpty(userAccompany1)&&userAccompany1.getStatus()==2){
             //再次申请
             accompanyMapper.updateAccmpanyInfo(userAccompany1);
            //修改证件信息
             accompanyDto.setAccompanyId(userAccompany1.getAccompanyId());
             accompanyMapper.updateEvidence(accompanyDto);
             accompanyMapper.updateAddress(accompanyDto);
             return true;
         }

            //生成陪诊id
            String accompanyId="";
            Random random = new Random();
            for (int i = 0; i < 8; i++) {
                accompanyId = String.valueOf(random.nextInt(10))+accompanyId;
            }
            accompanyDto.setAccompanyId(Integer.parseInt(accompanyId));//陪诊员编号
            accompanyDto.setUid(Integer.parseInt(userId));//陪诊员账号id
            accompanyMapper.insertAccompanyInfo(accompanyDto);//插入审核
            accompanyMapper.insertEvidence(accompanyDto);    //插入相关证明资料
            accompanyMapper.insertAddress(accompanyDto);    //插入地址
            return true;

    }

    /**
     * 陪诊员中心
     */
    @Override
    public Object accompanyCentre() {
        //根据userid 查询陪诊员信息
        String userId = commonUtil.getUserId(request);
        UserAccompany userAccompany = new UserAccompany();
        userAccompany.setUid(Integer.parseInt(userId));
      UserAccompanyDto userAccompanyDto= accompanyMapper.getUserInfoByUid(userAccompany);
        PersonalCenterVo personalCenterVo = new PersonalCenterVo();
      log.info(userAccompanyDto+"------>>>>>>>>>");
        if (BizEmpty(userAccompanyDto)) {
            TUser tUser = new TUser();
            tUser.setUid(Integer.parseInt(userId));
            TUser userInfoByUid = tUserMappers.getUserInfoByUid(tUser);
            personalCenterVo.setTUser(userInfoByUid);
            log.info(userInfoByUid+"______<<<<<<<<<");
            return personalCenterVo;

        }

   if (userAccompanyDto.getStatus()==1||userAccompanyDto.getStatus()==2){
       TUser tUser = new TUser();
       tUser.setUid(Integer.parseInt(userId));
       personalCenterVo.setUserAccompanyInfo(userAccompanyDto);
       return personalCenterVo;

   }
        //查询服务次数  根据陪诊id
        Integer serviceCont = accompanyReceiveOrderMapper.getContByAccompanyId(userAccompanyDto);
        //查询本月接单
        Integer MonthCount = accompanyReceiveOrderMapper.getNowToMonth(userAccompanyDto);
        //订单总收入  根据陪诊id
        AccompanyWallet accompanyWallet = new AccompanyWallet();
        accompanyWallet.setAccompanyId(userAccompanyDto.getAccompanyId());
        BigDecimal accompanyWalletRecode = accompanyWalletMapper.getWalletInfo(accompanyWallet);
         if (BizEmpty(accompanyWalletRecode)){
             accompanyWalletRecode = new BigDecimal("0");
         }
        //查询待服务有几单
//        AccompanyReceiveOrder accompanyReceiveOrder = new AccompanyReceiveOrder();
//        accompanyReceiveOrder.setAccompanyId(userAccompanyDto.getAccompanyId());
//        Integer receiveCount = accompanyReceiveStatusMapper.getOrderNoCountByStatus(accompanyReceiveOrder);
        Order order = new Order();
        order.setAccompanyId(userAccompanyDto.getAccompanyId());
       Integer  receivecount= orderMapper.getreceiveCount(order);
        //钱包
        AccompanyWallet  moneySum = accompanyWalletMapper.getMoneySum(accompanyWallet);
        if (BizEmpty(moneySum)){
            return personalCenterVo;
        }
        BigDecimal money = moneySum.getMoney();

        personalCenterVo.setMoney(money);//钱包总额
        personalCenterVo.setServiceCont(serviceCont);//服务总次数;
        personalCenterVo.setMonthCount(MonthCount);//本月接单数
        personalCenterVo.setReceiveCount(receivecount);//待服务订单数
        personalCenterVo.setAccompanyWalletRecode(accompanyWalletRecode);//订单收入总额
        personalCenterVo.setUserAccompanyInfo(userAccompanyDto);//用户信息
        return personalCenterVo;
    }

    /**
     * 钱包详情
     * */
    @Override
    public Object walletDetails() {
        String userId = commonUtil.getUserId(request);
        //根据userid 查询账户的金额
        UserAccompany userAccompany =  new UserAccompany();
        userAccompany.setUid(Integer.parseInt(userId));
        UserAccompany accompanyByUid = accompanyMapper.getAccompanyByUid(userAccompany);
        if (BizEmpty(accompanyByUid)){
            throw  new BizException(ApiResultCode.NOT_ACCOMPANY);
        }
        AccompanyWallet accompanyWallet = new AccompanyWallet();
        accompanyWallet.setAccompanyId(accompanyByUid.getAccompanyId());
        AccompanyWalletDto accompanyWalletDto= accompanyWalletMapper.getWalletDetails(accompanyWallet);//总收入
        if (!BizEmpty(accompanyWalletDto)){
            //查询本月收入
            AccompanyWalletDto accompanyWalletDtoMoth= accompanyWalletMapper.getMoneyByMoth(accompanyWallet);
            accompanyWalletDto.setMothMoney(accompanyWalletDtoMoth.getMothMoney());
            return accompanyWalletDto;
        }
        AccompanyWalletDto accompanyWalletDto1 = new AccompanyWalletDto();
        BigDecimal bigDecimal = new BigDecimal("0");
        accompanyWalletDto1.setMothMoney(bigDecimal);
        accompanyWalletDto1.setAwrMoney(bigDecimal);
        accompanyWalletDto1.setMoney(bigDecimal);
        return accompanyWalletDto1;
    }

   /**
    * 余额明细
    * */
    @Override
    public Object remainingBalance() {
        String userId = commonUtil.getUserId(request);
        UserAccompany userAccompany = new UserAccompany();
        userAccompany.setUid(Integer.parseInt(userId));
        UserAccompany accompanyByUid = accompanyMapper.getAccompanyByUid(userAccompany);
        if (BizEmpty(accompanyByUid)){
            throw  new BizException(ApiResultCode.NOT_ACCOMPANY);
        }
        //根据陪诊id 查询余额明细
        AccompanyWallet accompanyWallet = new AccompanyWallet();
        accompanyWallet.setAccompanyId(accompanyByUid.getAccompanyId());
   //   AccompanyWalletDto accompanyWalletDto =  accompanyWalletMapper.remainingBalance(accompanyWallet);
      //查出总金额  在查出进行中的钱
        AccompanyWallet moneySum = accompanyWalletMapper.getMoneySum(accompanyWallet);//总金额
        //再查出未入账的金额
       AccompanyWalletRecode  accompanyWalletDto  =  accompanyWalletMapper.getnotArriveToOurAccount(accompanyWallet);
       BigDecimal  notMoney  = new BigDecimal("0.00");
       if (!BizEmpty(accompanyWalletDto)){
           notMoney= accompanyWalletDto.getMoney();//未入账的钱
         }
      AccompanyWalletDto accompanyWalletDto1 = new AccompanyWalletDto();
       accompanyWalletDto1.setWithdrawal(moneySum.getMoney());
       accompanyWalletDto1.setNoAccount(notMoney);
       accompanyWalletDto1.setAwrMoney(moneySum.getMoney());
       accompanyWalletDto1.setMoney(moneySum.getMoney());
        return accompanyWalletDto1;
    }

    @Override
    public PageInfo<AccompanyWalletDto> fiveDetails() {
        //查询我的 钱包记录 desc
        PageHelper.startPage(pageUtils.getPage().getPageNum(),pageUtils.getPage().getPageSize());
        String userId = commonUtil.getUserId(request);
        UserAccompany userAccompany = new UserAccompany();
        userAccompany.setUid(Integer.parseInt(userId));
        UserAccompany accompanyByUid = accompanyMapper.getAccompanyByUid(userAccompany);
        if (BizEmpty(accompanyByUid)){
            throw  new BizException(ApiResultCode.NOT_ACCOMPANY);
        }
        AccompanyWallet accompanyWallet = new AccompanyWallet();
        accompanyWallet.setAccompanyId(accompanyByUid.getAccompanyId());
        //最近五条明细
        List<AccompanyWalletDto> fiveDetail = new ArrayList<>();
       fiveDetail = accompanyWalletMapper.getFiveDetail(accompanyWallet);

        return new PageInfo<>(fiveDetail);
    }

    /**
     * 邀请记录
     * */
    @Override
    public PageInfo<AccompanyInviteDto> invitedToRecord(AccompanyInvite accompanyInvite) {//陪诊id
        PageHelper.startPage(pageUtils.getPage().getPageNum(),pageUtils.getPage().getPageSize());
    List<AccompanyInviteDto> accompanyInviteDtoList = accompanyInviteMapper.getInviteRecord(accompanyInvite);
          UserAccompany userAccompany = new UserAccompany();
          Integer sum = 0;
        for (AccompanyInviteDto accompanyInviteDto : accompanyInviteDtoList) {
            //根据uid查询陪诊id 和接单数
            userAccompany.setUid(accompanyInviteDto.getUid());
          AccompanyReceiveOrderDto accompanyReceiveOrder=   accompanyReceiveOrderMapper.getOrderSum(userAccompany);
           accompanyInviteDto.setCount(accompanyReceiveOrder.getCount());
           //推荐奖励 一单五元
            Integer bonus = accompanyReceiveOrder.getCount() * money;//奖励单金额
            accompanyInviteDto.setBonus(bonus);//此用户的给你的奖励金额
            sum = bonus+sum;

        }
        if (accompanyInviteDtoList.size()<=0){
            return new PageInfo<>(accompanyInviteDtoList);
        }
        accompanyInviteDtoList.get(0).setFriend( accompanyInviteDtoList.size());//好友总数
        accompanyInviteDtoList.get(0).setSumBonus(sum);//好友总共给你赚的钱
        return new PageInfo<>(accompanyInviteDtoList);
    }

    private boolean notNull(AccompanyDto accompanyDto) {
        if (BizEmpty(accompanyDto.getIdCard())) {
            return false;
        }
        if (BizEmpty(accompanyDto.getName())) {
            return false;
        }
        if (BizEmpty(accompanyDto.getSex())) {
            return false;
        }
        if (BizEmpty(accompanyDto.getPhone())) {
            return false;
        }
        if (BizEmpty(accompanyDto.getSide())) {
            return false;
        }
        if (BizEmpty(accompanyDto.getMain())) {
            return false;
        }
        if (BizEmpty(accompanyDto.getHealth())) {
            return false;
        }
        if (BizEmpty(accompanyDto.getLatitude())){
            return false;
        }
        if (BizEmpty(accompanyDto.getLongitude())){
            return false;
        }
        if (BizEmpty(accompanyDto.getAddress())){
            return false;
        }
        return true;

    }
}
